<!--
 * @Description: 
 * @Author: 胡涛
 * @Date: 2023-09-13 21:15:55
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-10-25 11:52:28
-->
<template>
  <a-modal
    :open="visible"
    :keyboard="false"
    :maskClosable="false"
    :title="title"
    @cancel="onCancel"
    @ok="onSubmit"
    :confirmLoading="submitLoading"
    :width="800"
  >
    <a-form ref="formRef" v-bind="formLayout" :model="model" :rules="rules">
      <a-form-item label="菜单分组" prop="groupName">
        <dictionary-select
          v-model:value="model.groupName"
          name="Platform.MenuGroup"
          :disabled="isEdit"
        ></dictionary-select>
      </a-form-item>
      <a-form-item label="上级分类" prop="parentId">
        <a-tree-select
          :treeData="categoryItems"
          v-model:value="model.parentId"
          clear
        >
        </a-tree-select>
      </a-form-item>
      <a-form-item label="菜单类型" prop="menuType">
        <enum-select
          v-model:value="model.menuType"
          name="MenuType"
        ></enum-select>
      </a-form-item>
      <a-form-item label="菜单名称" prop="displayName">
        <a-input v-model:value="model.displayName"> </a-input>
      </a-form-item>
      <a-form-item label="关联权限" prop="permissionName">
        <a-cascader
          v-model:value="model.permissionNames"
          :options="permissionOptions"
          :changeOnSelect="true"
          :fieldNames="{
            children: 'children',
            label: 'displayName',
            key: 'name',
            value: 'name',
          }"
          allowClear
          :virtual="false"
          @change="onPermissionNameChanged"
        >
        </a-cascader>
      </a-form-item>
      <a-form-item label="图标" prop="icon">
        <a-input v-model:value="model.icon"> </a-input>
      </a-form-item>
      <a-form-item label="菜单地址" prop="url">
        <a-input v-model:value="model.url"> </a-input
      ></a-form-item>

      <a-form-item label="启用状态" prop="status">
        <a-switch v-model:checked="model.status"></a-switch>
      </a-form-item>
      <a-form-item label="排序号" prop="sortIndex">
        <a-input-number v-model:value="model.sortIndex"></a-input-number>
      </a-form-item>
      <a-form-item label="备注" prop="remarks">
        <a-input v-model:value="model.remarks"></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { SystemMenuDto } from "@/api/system/types";
import { useFormPage } from "@/helpers/pages";
import { FormInstance } from "ant-design-vue";
import { computed, onMounted, ref, watch } from "vue";
import api from "@/api/system/menu";
import { EmptyGuid } from "@/helpers/contants";
import { useAppStore } from "@/store";
import { storeToRefs } from "pinia";
const formRef = ref<FormInstance>();
const emits = defineEmits(["update:visible", "close", "success"]);
const appStore = useAppStore();

const props = defineProps({
  id: String,
  visible: { type: Boolean, default: false },
  action: {
    type: String,
    default: "create",
  },
  item: {
    type: Object,
    default() {
      return {};
    },
  },
  categoryItems: { type: Array, required: true },
});

const { model, rules, formLayout, loading, submitLoading } = useFormPage<
  SystemMenuDto,
  string
>({
  rules: {
    groupName: [{ required: true, message: "请选择菜单分组信息" }],
    menuType: [{ required: true, message: "请选择菜单节点类型" }],
    displayName: [{ required: true, message: "请输入菜单显示名称信息" }],
  },
  model: {
    groupName: "",
    menuType: 1,
    parentId: EmptyGuid,
    displayName: "",
    permissionName: "",
    icon: "desktop",
    url: "",
    remarks: "",
    sortIndex: 0,
    status: true,
  },
});

const permissionOptions = ref<any>([]);

const onPermissionNameChanged = (val) => {
  if (val.length) {
    model.permissionName = val[val.length - 1];
  } else {
    model.permissionName = "";
  }
};

onMounted(async () => {
  permissionOptions.value = await appStore.getPermissionDeninitions();
});

const isEdit = computed(() => {
  return props.action === "edit";
});

/**
 * 弹窗标题
 */
const title = computed(() => {
  return isEdit.value ? "修改菜单信息" : "添加菜单信息";
});

/**
 * 加载数据
 */
const loadData = () => {
  if (isEdit.value) {
    loading.value = true;
    api.get(props.id).then((res) => {
      let permissionNames = [];
      if (res.permissionName) {
        let index = res.permissionName.indexOf(".");
        while (index !== -1) {
          permissionNames.push(res.permissionName.substring(0, index));
          index = res.permissionName.indexOf(".", index + 1);
        }
        permissionNames.push(res.permissionName);
      }
      Object.assign(model, { permissionNames }, res);
      loading.value = false;
    });
  }
};

/**
 * 提交
 */
const onSubmit = () => {
  emits("success");
  formRef.value.validate().then(() => {
    let request = isEdit.value
      ? api.update(props.id, model)
      : api.create(model);
    submitLoading.value = true;
    request
      .then((res) => {
        emits("success", res);
        emits("update:visible", false);
        emits("close");
      })
      .finally(() => {
        submitLoading.value = false;
      });
  });
};

/**
 * 取消
 */
const onCancel = () => {
  emits("update:visible", false);
  emits("close");
};

watch(
  () => props.visible,
  (val: boolean) => {
    console.log("visible changed,val,", val);
    val && loadData();
  },
  { immediate: true }
);
</script>

<style lang="less" scoped></style>
